package com.good.msgsys.controller;

import com.good.msgsys.dto.Result;
import com.good.msgsys.dto.ResultCode;
import com.good.msgsys.entity.User;
import com.good.msgsys.entity.request.UserVo;
import com.good.msgsys.entity.response.LoginRes;
import com.good.msgsys.entity.response.UserInfo;
import com.good.msgsys.service.UserService;
import com.good.msgsys.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 登录相关
 *
 * @author junlong
 * @date 2021/1/5 19:50
 */
@Api(tags = "登录相关")
@RestController
@RequestMapping("/api")
public class LoginController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    // 用户登录
    @ApiOperation("用户登录，登录成功返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<LoginRes> login(@ApiParam(value = "用户登录信息", required = true) @RequestBody UserVo userVo) {
        // 1.获取请求参数
        String account = userVo.getAccount();
        String password = userVo.getPassword();
        // 2.使用账号account查询用户
        User user = userService.findByAccount(account);
        // 3.比较数据库查询结果
        if (user == null || !user.getPassword().equals(password)) {
            // 登录失败
            return new Result<>(ResultCode.NAME_OR_PASSWORD_ERROR);
        } else {
            // 登录成功
            // 4.生成token，并返回给前端
            String token = jwtUtil.createJwt(user.getId(), user.getName(), null);
            LoginRes loginRes = new LoginRes(user.getId(), user.getName(), token);
            return new Result<>(ResultCode.SUCCESS, loginRes);
        }
    }

    /**
     * 用户登录成功之后，获取用户信息
     * 1.获取用户id
     * 2.根据用户id查询用户
     * 3.构建返回值对象
     * 4.响应
     */
    @ApiOperation("获取当前登录用户的信息")
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public Result<UserInfo> profile() {
        String userid = claims.getId();
        User user = userService.findById(userid);
        UserInfo userInfo = new UserInfo(user);
        return new Result<>(ResultCode.SUCCESS, userInfo);
    }
}
